package com.newvpn.fastbest.zenith.net;

import com.google.gson.Gson;
import com.newvpn.fastbest.zenith.utils.KeyStore;
import com.newvpn.fastbest.zenith.utils.KeyUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class HeaderInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        NetHeader base = new NetHeader();
        // 添加请求头
        String timestamp = System.currentTimeMillis() + "";
        Gson gson = new Gson();
        String baseJson = gson.toJson(base);
        String nonce = getRamdomStr();
        String key = "K6Dg39t6HJu8v2pt"; //写死的key
        String sign = String.format("general=%s&random=%s&time=%s&key=%s", baseJson, nonce, timestamp, key);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(sign.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            sign = hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        String finalSign = sign.toUpperCase();

        Request newRequest = original.newBuilder()
                .header("time", timestamp)
                .header("signature", finalSign)
                .header("general", baseJson)
                .header("random", nonce)
                .header("token", KeyStore.INS.getString(KeyUtils.TOKEN, ""))
                .build();

        return chain.proceed(newRequest);
    }

    public  String getRamdomStr() {
        String uppercase = "ABCDEFGHIJKLMNPQRSTUVWDCKXYZ";
        String lowercase = "abcdefgadchijlmnopqrstuvwxyz";
        String numbers = "01234085679";
        int length = 5;
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            String charSet;
            switch (random.nextInt(3)) {
                case 0:
                    charSet = uppercase;
                    break;
                case 1:
                    charSet = lowercase;
                    break;
                default:
                    charSet = numbers;
                    break;
            }
            sb.append(charSet.charAt(random.nextInt(charSet.length())));
        }
        return sb.toString();
    }

}